package com.le.tester.controller;

import com.le.tester.common.ServerResponse;
import com.le.tester.common.enums.ResponseCode;
import com.le.tester.entity.Product;
import com.le.tester.sevice.ProductService;
import com.le.tester.utils.RequestLimitUtil;
import com.le.tester.utils.auth.RequestLimit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 描述：产品的控制层
 */
@Controller
@RequestMapping("/product/")
public class ProductController {

    private static final Logger LOG = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    @Autowired
    private RequestLimitUtil requestLimitUtil;

    @Autowired
    private HttpServletRequest request;

    @ResponseBody
    @RequestMapping("getProductInfo")
    public ServerResponse<Map<String, List<Product>>> getProductInfo() {
//        boolean isLimit = requestLimitUtil.requestLimit(4L, 1000L, request);
//        if (isLimit) {
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.REQUEST_API_LIMIT.getCode(),
//                    ResponseCode.REQUEST_API_LIMIT.getDesc());
//        }
        try {
            Map<String, List<Product>> productInfo = productService.getProductInfo();
            return ServerResponse.createBySuccess(productInfo);
        } catch (Exception ex) {
            LOG.info("获取产品的信息失败，{}", ex.getMessage());
            return ServerResponse.createByError();
        }
    }

    @ResponseBody
    @RequestMapping("saveProduct")
    public ServerResponse<String> saveProduct() {
        return null;
    }


    //根据产品主键获取产品信息
    @ResponseBody
    @RequestMapping("get/{productId}")
    public ServerResponse<Product> getProductInfoById(@PathVariable("productId") Long productId) {

        //异常现在由全局进行捕获
        return productService.getProductInfoById(productId);
    }

    //保存产品信息
    @ResponseBody
    @RequestMapping("save")
    public ServerResponse<Long> saveProduct(@RequestBody Product product) {

        //异常现在由全局进行捕获
        return productService.saveProduct(product);
    }
}
